package com.liang.lollipop.lreader.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.BaseTransientBottomBar;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.liang.lollipop.lreader.R;
import com.liang.lollipop.lreader.base.BaseActivity;
import com.liang.lollipop.lreader.base.BaseHolder;
import com.liang.lollipop.lreader.bean.AppInfo;
import com.liang.lollipop.lreader.bean.HistorBean;
import com.liang.lollipop.lreader.util.AppInfoUtil;
import com.liang.lollipop.lreader.util.HistorDAO;
import com.liang.lollipop.lreader.util.LItemTouchHelper;
import com.liang.lollipop.lreader.util.TaskUtils;

import java.util.ArrayList;
import java.util.Objects;

/**
 * 历史记录的Activity
 * @author Lollipop
 */
public class HistoricalRecordActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener {

    private SwipeRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private Adapter adapter;

    private int page = 0;
    private boolean isLoading = false;
    private HistorDAO historDAO;

    private ArrayList<HistorBean> historBeen;
    private ArrayList<AppInfo> appInfos;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_historical_record);
        setToolBar(R.id.activity_historical_record_toolbar);
        initView();
        queryAppInfoList();
    }

    @Override
    protected void onResume() {
        super.onResume();
        onRefresh();
    }

    private void initView(){
        historBeen = new ArrayList<>();
        appInfos = new ArrayList<>();
        historDAO = new HistorDAO(this);

        refreshLayout = (SwipeRefreshLayout) findViewById(R.id.activity_historical_record_refresh);
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setColorSchemeResources(R.color.colorAccent,R.color.colorRed);
        recyclerView = (RecyclerView) findViewById(R.id.activity_historical_record_recyclerview);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        LItemTouchHelper helper = LItemTouchHelper.newInstance(recyclerView,this);
        helper.setCanSwipe(true);
        helper.setCanDrag(false);
        recyclerView.setAdapter(adapter = new Adapter(LayoutInflater.from(this),historBeen,appInfos,helper));
        scrollWithRecyclerView(recyclerView);
    }

    @Override
    public void onRefresh() {
        if(isLoading)
            return;
        refreshLayout.setRefreshing(true);
        page = 0;
        isLoading = true;
        getData();
    }

    @Override
    public void onMore() {
        super.onMore();
        if(isLoading)
            return;
        page++;
        isLoading = true;
        getData();
    }

    private void getData(){
        TaskUtils.addTask(new TaskUtils.OnHandlerCallBack<ArrayList<HistorBean>,Object>(handler) {
            @Override
            public void onUISuccess(ArrayList<HistorBean> result) {
                isLoading = false;
                if(refreshLayout!=null)
                    refreshLayout.setRefreshing(false);
                if(page==0)
                    historBeen.clear();
                if(result!=null)
                    historBeen.addAll(result);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onUIError(Exception e, int code, String msg) {
                T(getString(R.string.error_history_list)+e.toString());
                isLoading = false;
                if(refreshLayout!=null)
                    refreshLayout.setRefreshing(false);
            }

            @Override
            public ArrayList<HistorBean> onBackground(Object... args) throws Exception {
                HistorDAO dao = (HistorDAO) args[0];
                int p = (int) args[1];
                return dao.selectByPage(p);
            }
        },historDAO,page);
    }

    private class Adapter extends RecyclerView.Adapter<HistoryHolder> implements IconCallBack{

        private LayoutInflater inflater;
        private ArrayList<HistorBean> dataBeen;
        private ArrayList<AppInfo> appInfos;
        private LItemTouchHelper helper;

        Adapter(LayoutInflater inflater, ArrayList<HistorBean> dataBeen, ArrayList<AppInfo> appInfos, LItemTouchHelper helper) {
            this.inflater = inflater;
            this.dataBeen = dataBeen;
            this.appInfos = appInfos;
            this.helper = helper;
        }

        @Override
        public HistoryHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            HistoryHolder holder = HistoryHolder.newInstance(inflater,parent);
            holder.setHelper(helper);
            holder.setCallBack(this);
            return holder;
        }

        @Override
        public void onBindViewHolder(HistoryHolder holder, int position) {
            holder.onBind(dataBeen.get(position));
        }

        @Override
        public int getItemCount() {
            if(dataBeen!=null)
                return dataBeen.size();
            return 0;
        }

        @Override
        public Drawable getIcon(String pkg) {
            for(AppInfo info : appInfos){
                if(info.pkgName.equals(pkg)){
                    return info.appIcon;
                }
            }
            return null;
        }
    }

    private static class HistoryHolder extends BaseHolder{

        private static final int LAYOUT_ID = R.layout.item_history;

        private TextView nameView;
        private TextView pkgView;
        private TextView timeView;
        private ImageView iconView;

        private IconCallBack callBack;

        static HistoryHolder newInstance(LayoutInflater inflater, ViewGroup group){
            return new HistoryHolder(inflater.inflate(LAYOUT_ID,group,false));
        }

        HistoryHolder(View itemView) {
            super(itemView);
            nameView = (TextView) itemView.findViewById(R.id.item_history_name);
            pkgView = (TextView) itemView.findViewById(R.id.item_history_pkg);
            timeView = (TextView) itemView.findViewById(R.id.item_history_time);
            iconView = (ImageView) itemView.findViewById(R.id.item_history_icon);
            canSwipe = true;
        }

        void setCallBack(IconCallBack callBack) {
            this.callBack = callBack;
        }

        void onBind(HistorBean bean) {
            super.onBind(bean);
            nameView.setText(bean.name);
            pkgView.setText(bean.pkg);
            timeView.setText(bean.time);
            iconView.setImageDrawable(callBack.getIcon(bean.pkg));
        }

    }

    private interface IconCallBack{
        Drawable getIcon(String pkg);
    }

    private void queryAppInfoList(){
        TaskUtils.addTask(new TaskUtils.OnHandlerCallBack<ArrayList<AppInfo>,Context>(handler) {

            @Override
            public void onUISuccess(ArrayList<AppInfo> result) {
                appInfos.clear();
                if(result!=null)
                    appInfos.addAll(result);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onUIError(Exception e, int code, String msg) {
                T(getString(R.string.error_model_list)+e.getLocalizedMessage());
            }

            @Override
            public ArrayList<AppInfo> onBackground(Context... args) throws Exception {
                Context context = args[0];
                return AppInfoUtil.queryAppInfoNoIntent(context);
            }
        },this);
    }

    @Override
    public void onSwiped(int adapterPosition) {
        super.onSwiped(adapterPosition);
        HistorBean historBean = historBeen.remove(adapterPosition);
        adapter.notifyItemRemoved(adapterPosition);
        Snackbar.make(recyclerView, R.string.deleted,Snackbar.LENGTH_LONG)
                .setAction(R.string.undo, new RecallClickListener(adapterPosition,historBean,adapter,historBeen))
                .addCallback(new SwipedCallback(historDAO,historBean)).show();
    }

    private class SwipedCallback extends BaseTransientBottomBar.BaseCallback<Snackbar>{
        private HistorDAO dao;
        private HistorBean bean;

        SwipedCallback(HistorDAO dao, HistorBean bean) {
            this.dao = dao;
            this.bean = bean;
        }

        @Override
        public void onDismissed(Snackbar transientBottomBar, int event) {
            super.onDismissed(transientBottomBar, event);
            if(event==DISMISS_EVENT_ACTION)
                return;
            dao.delete(bean.id);
        }
    }

    private class RecallClickListener implements View.OnClickListener{

        private int adapterPosition;
        private HistorBean historBean;
        private Adapter adapter;
        private ArrayList<HistorBean> data;

        RecallClickListener(int adapterPosition, HistorBean historBean, Adapter adapter, ArrayList<HistorBean> data) {
            this.adapterPosition = adapterPosition;
            this.historBean = historBean;
            this.adapter = adapter;
            this.data = data;
        }

        @Override
        public void onClick(View v) {
            data.add(adapterPosition,historBean);
            adapter.notifyItemInserted(adapterPosition);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_history,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId()==R.id.menu_history_clear_all){
            new AlertDialog.Builder(this)
                    .setTitle(getString(R.string.hint))
                    .setMessage(R.string.alert_delete_all)
                    .setNegativeButton(getString(R.string.refused), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            deleteAll();
                            dialog.dismiss();
                        }
                    })
                    .show();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void deleteAll(){
        TaskUtils.addTask(new TaskUtils.OnHandlerCallBack<Boolean,HistorDAO>(handler) {
            @Override
            public void onUISuccess(Boolean result) {
                if(result!=null&&result){
                    historBeen.clear();
                }
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onUIError(Exception e, int code, String msg) {
                T(getString(R.string.error_delete_history));
            }

            @Override
            public Boolean onBackground(HistorDAO... args) throws Exception {
                HistorDAO dao = args[0];
                dao.deleteAll();
                return true;
            }
        },historDAO);
    }

}
